package cn.com.yusys.yusp.admin.web.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.com.yusys.yusp.admin.domain.AdminSmLookupItem;
import cn.com.yusys.yusp.admin.service.AdminSmLookupItemService;
import cn.com.yusys.yusp.commons.exception.MessageConstants;
import cn.com.yusys.yusp.commons.service.CommonService;
import cn.com.yusys.yusp.commons.web.rest.CommonResource;
import cn.com.yusys.yusp.commons.web.rest.dto.ResultDto;
import io.swagger.annotations.ApiParam;

/**
 * 数据字典维护。
 *
 * <pre>
 * 	   20191113:添加字典项排序功能
 *     20190525:添加批量更新数据字典缓存。
 * </pre>
 *
 * @author liaoxd
 * @author weimei
 * @since 1.1.2
 */
@RestController
@RequestMapping("/api/adminsmlookupitem")
public class AdminSmLookupItemResource extends CommonResource<AdminSmLookupItem, String> {

	@Autowired
	private AdminSmLookupItemService adminSmLookupItemService;

	private final Logger log = LoggerFactory.getLogger(AdminSmLookupItemResource.class);

    @Override
    protected CommonService getCommonService() {
        return this.adminSmLookupItemService;
    }

    /**
	 * @方法名称: getLookupCodeList
	 * @方法描述: redis定制数据字典内容接口
	 * @参数与返回说明:
	 * @算法描述:
	 */
	@GetMapping("/list")
	public ResultDto<Map<String, List<Map<String, String>>>> getLookupCodeList(@ApiParam(value = "mult lookupcode ", required = true) @RequestParam String lookupCodes) {
		log.debug("REST request to get Object : {}", lookupCodes);
		// Map<String,List<Map<String,String>>> object =
		// this.adminSmLookupItemService.getLookupCodeList(lookupCodes);
		Map<String, List<Map<String, String>>> object = new HashMap<String, List<Map<String, String>>>();
		if (lookupCodes.contains(",")) {
			String[] idstr = lookupCodes.split(",");
			for (int id = 0; id < idstr.length; id++) {
				List<Map<String, String>> lookupList = this.adminSmLookupItemService.getLookupInfoWithCache(idstr[id]);
				object.put(idstr[id], lookupList);
			}
		} else {
			object.put(lookupCodes, this.adminSmLookupItemService.getLookupInfoWithCache(lookupCodes));
		}
		return new ResultDto<Map<String, List<Map<String, String>>>>(object);

	}

	/**
	 * @方法名称: getLookupCode
	 * @方法描述: 前台WEB加载字典（需要在此封装逻辑，不然service层无法用到原子REDIS查询）
	 * @参数与返回说明:
	 * @算法描述:
	 */
	@GetMapping("/weblist")
	public ResultDto<Map<String, List<Map<String, String>>>> getMultLookupCode(@ApiParam(value = "mult lookupcode ", required = true) @RequestParam String lookupCodes) {
		log.debug("REST request to get Object : {}", lookupCodes);
		Map<String, List<Map<String, String>>> object = new HashMap<String, List<Map<String, String>>>();
		if (lookupCodes.contains(",")) {
			String[] idstr = lookupCodes.split(",");
			for (int id = 0; id < idstr.length; id++) {
				Map<String, List<Map<String, String>>> map = this.adminSmLookupItemService.getLookupCodeList(idstr[id]);
				object.putAll(map);
			}
		} else {
			object = this.adminSmLookupItemService.getLookupCodeList(lookupCodes);
		}
		return new ResultDto<Map<String, List<Map<String, String>>>>(object.size(), object);
	}


	/**
	 * @方法名称: delete
	 * @方法描述: 删除
	 * @参数与返回说明:
	 * @算法描述:
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("/delete")
	public ResultDto<Integer> delete(@RequestBody String lookupItem) {
		log.debug("删除数据字典内容：{}", lookupItem);
		ObjectMapper jsonObj = new ObjectMapper();
		int result = 0;
		ResultDto<Integer> resultDto = new ResultDto<>();
		try {
			Map<String, Object> map = jsonObj.readValue(lookupItem, Map.class);
			result = this.adminSmLookupItemService.deleteWithCache(map.get("lookupItemId").toString(), map.get("lookupCode").toString());
			resultDto.setData(result);
			resultDto.setMessage("删除数据字典内容成功!");
		} catch (Exception e) {
			resultDto.setCode(500);
			resultDto.setMessage(e.getMessage());
		}
		return resultDto;

	}

	/**
	 * 新建字典项
	 *
	 * @param t
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/createitem")
	public ResultDto<Map<String, List<Map<String, String>>>> createItem(@ApiParam(value = "Object", required = true) @RequestBody AdminSmLookupItem t) throws Exception {
		log.debug("REST request to update Object : {}", t);
		ResultDto<Map<String, List<Map<String, String>>>> resultDto = new ResultDto<>();
		try {
			Map<String, List<Map<String, String>>> result = adminSmLookupItemService.createWithCache(t);
			resultDto.setData(result);
			resultDto.setMessage("新增数据字典内容成功!");
		} catch (Exception e) {
			resultDto.setCode(500);
			resultDto.setMessage(e.getMessage());
		}
		return resultDto;
	}

	/**
	 * @方法名称: updateSelective
	 * @方法描述: 修改接口
	 * @参数与返回说明:
	 * @算法描述:
	 */
	@PostMapping("/updates")
	public ResultDto<Map<String, List<Map<String, String>>>> updateSelective(@ApiParam(value = "Object", required = true) @RequestBody AdminSmLookupItem t) throws Exception {
		log.debug("REST request to update Object : {}", t);
		ResultDto<Map<String, List<Map<String, String>>>> resultDto = new ResultDto<>();
		try {
			Map<String, List<Map<String, String>>> result = adminSmLookupItemService.updateWithCache(t);
			resultDto.setData(result);
			resultDto.setMessage("修改数据字典内容成功!");
		} catch (Exception e) {
			resultDto.setCode(500);
			resultDto.setMessage(e.getMessage());
		}
		return resultDto;
	}


	/**
	 * @方法名称: getItemListBylookupcode
	 * @方法描述: 单个类别查询List-页面
	 * @参数与返回说明:
	 * @算法描述:
	 */
	@GetMapping("/listbylookupcode")
	public ResultDto<List<Map<String, String>>> getItemListBylookupcode(@ApiParam(value = "sigle lookupcode ", required = true) @RequestParam String lookupCode) {
		log.debug("REST request to delete Object : {}", lookupCode);
		List<Map<String, String>> object = this.adminSmLookupItemService.getListByCodeForTree(lookupCode);
		return new ResultDto<List<Map<String, String>>>(object);

	}

    /**
     * 批量更新数据字典缓存。
     * 仅用于非页面操作时更新Redis缓存。可能较慢。
     * 当某个字典更新失败会提示对应code信息，请尝试手动更新。
     *
     * @return
     */
    @GetMapping("/refreshitem")
    public ResultDto<String> refreshItem() {
        StringBuilder builder = new StringBuilder();
        // 20191128 wangyang13
 		// 使用RedisHelper的keys方法代替stringRedisTemplate的keys方法扫描Key
 		// Set<String> keysList =
 		// stringRedisTemplate.keys("AdminSmLookupItem::*");
 		//List<String> keysList = redisHelper.keys("AdminSmLookupItem::*");
        //stringRedisTemplate.delete(keysList);
        adminSmLookupItemService.cleanAdminSmLookupItemCache();
        //查询所有数据字典信息
        Map<String, List<Map<String, String>>> map = adminSmLookupItemService.getItemList();
        map.forEach((key, value) -> {
            try {
                //放入单个数据字典信息到缓存
                adminSmLookupItemService.putItemCache(key, value);
            } catch (Exception e) {
                //记录更新缓存失败的code
                builder.append(key).append(",");
            }
        });
        ResultDto<String> result = new ResultDto<String>();
        if (StringUtils.isEmpty(builder)) {
            result.setCode(MessageConstants.RET_CODE_20100000);
            result.setMessage("数据字典缓存更新成功!");
        } else {       	
            //builder.insert(0, "数据字典缓存更新:{");
            //builder.append("}失败!");
        	List<Object> i18nData = new ArrayList<Object>();
        	i18nData.add(builder.toString());
            result.setCode(MessageConstants.RET_CODE_20100001);
            result.setI18nData(i18nData);
            result.setMessage("数据字典缓存更新:{"+builder.toString()+"}失败!");
        }
        return result;

    }

    /**
	 * @方法名称: getLookupItemCode
	 * @方法描述: 获取数据字典项代码
	 * @参数与返回说明: lookupCodes:数据字典英文别名
	 * @算法描述:
	 */
	@GetMapping("/getLookupItemCode")
	public List<String> getLookupItemCode(@RequestParam String lookupCodes) {
		List<String> lookupItemlist = new ArrayList<String>();
		// 查询对应数据字典信息
		Map<String, List<Map<String, String>>> object = this.adminSmLookupItemService.getLookupCodeList(lookupCodes);
		if (object != null && object.containsKey(lookupCodes)) {
			List<Map<String, String>> lookupItem = object.get(lookupCodes);
			if (lookupItem != null && lookupItem.size() > 0) {
				for (Map<String, String> map : lookupItem) {
					lookupItemlist.add(map.get("key"));
				}
			}
		}
		return lookupItemlist;
	}

	/**
	 * 根据字典项类型返回字典项的字典码和字典码名称
	 * @param lookupCode 字典项
	 * @return
	 */
	@GetMapping("/getlookupcode")
	public Map<String, String> getLookupCode(@ApiParam(value = "lookupcode", required = true) @RequestParam String lookupCode) {
		List<Map<String, String>> object = new ArrayList<Map<String, String>>();
		Map<String, String> resultMap = new HashMap<String, String>();
		if (StringUtils.isNotBlank(lookupCode)) {
			Map<String, List<Map<String, String>>> lookupCodeList = this.adminSmLookupItemService.getLookupCodeList(lookupCode);
			for (Entry<String, List<Map<String, String>>> entry : lookupCodeList.entrySet()) {
				if (entry.getValue() != null) {
					object = entry.getValue();
					Iterator<Map<String, String>> iterator = object.iterator();
					while (iterator.hasNext()) {
						Map<String, String> tempMap = iterator.next();
						resultMap.put(tempMap.get("key"), tempMap.get("value"));
					}
					break;
				}
			}
		}
		return resultMap;
	}

	/**
	 * 根据字典项和字典码获取字典码名称
	 * @param lookupCode 字典项
	 * @param lookupItemCode 字典码
	 * @return
	 */
	@GetMapping("/getlookupitemname")
	public String getLookupItemName(@ApiParam(value = "lookupcode", required = true) @RequestParam String lookupCode,
			@ApiParam(value = "lookupitemcode", required = true) @RequestParam String lookupItemCode) {
		String lookupItemName = "";
		List<Map<String, String>> object = new ArrayList<Map<String, String>>();
		if (StringUtils.isNotBlank(lookupCode)) {
			Map<String, List<Map<String, String>>> lookupCodeList = this.adminSmLookupItemService.getLookupCodeList(lookupCode);
			for (Entry<String, List<Map<String, String>>> entry : lookupCodeList.entrySet()) {
				if (entry.getValue() != null) {
					object = entry.getValue();
					Iterator<Map<String, String>> iterator = object.iterator();
					while (iterator.hasNext()) {
						Map<String, String> tempMap = iterator.next();
						if (lookupItemCode.equals(tempMap.get("key"))) {
							lookupItemName = tempMap.get("value");
							break;
						}
					}
					break;
				}
			}
		}
		return lookupItemName;
	}
}
